import random
import pygame
from pygame.locals import *

pygame.init()

# 游戏设置
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()


# 玩家和敌人类
class Player:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.width = 50
        self.height = 50
        self.color = (0, 128, 255)

    def move(self, dx, dy):
        self.x += dx
        self.y += dy

    def draw(self):
        pygame.draw.rect(screen, self.color, (self.x, self.y, self.width, self.height))

class Enemy:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.width = 50
        self.height = 50
        self.color = (255, 0, 0)

    def move(self, target_x, target_y):
        # 简单的敌人AI：朝玩家靠近
        if self.x < target_x:
            self.x += 1
        if self.x > target_x:
            self.x -= 1
        if self.y < target_y:
            self.y += 1
        if self.y > target_y:
            self.y -= 1

    def draw(self):
        pygame.draw.rect(screen, self.color, (self.x, self.y, self.width, self.height))


def main():
    player = Player(100, 100)
    enemies = [Enemy(500, 500)]
    running = True
    while running:
        screen.fill((0, 0, 0))  # 清屏
        for event in pygame.event.get():
            if event.type == QUIT:
                running = False

        # 控制玩家移动
        keys = pygame.key.get_pressed()
        if keys[K_LEFT]: player.move(-5, 0)
        if keys[K_RIGHT]: player.move(5, 0)
        if keys[K_UP]: player.move(0, -5)
        if keys[K_DOWN]: player.move(0, 5)

        # 敌人移动
        for enemy in enemies:
            enemy.move(player.x, player.y)

        # 绘制玩家和敌人
        player.draw()
        for enemy in enemies:
            enemy.draw()

        pygame.display.flip()
        clock.tick(30)


if __name__ == '__main__':
    main()
